using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Extensions.Logging;
using NLog;
using System.Management;

namespace LocalDns.UI
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private bool _serviceRunning = false;
        private readonly HttpClient _httpClient;
        private bool _isServiceRunning = false;
        private List<DnsRecordViewModel> _dnsRecords = new List<DnsRecordViewModel>();
        private List<QueryLogViewModel> _recentQueries = new List<QueryLogViewModel>();
        private DateTime? _serviceStartTime;
        private System.Threading.Timer _refreshTimer;
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private const string SERVICE_PROCESS_NAME = "LocalDnsService";
        

        // 日志相关成员变量
        private FileSystemWatcher? _logFileWatcher;
        private string? _currentLogFilePath;
        private long _lastLogFilePosition = 0;
        private const int MAX_LOG_LINES = 1000;

        /// <summary>
        /// 服务运行状态
        /// </summary>
        public bool ServiceRunning
        {
            get => _serviceRunning;
            set
            {
                if (_serviceRunning != value)
                {
                    _serviceRunning = value;
                    _isServiceRunning = value;
                    OnPropertyChanged(nameof(ServiceRunning));
                }
            }
        }
        
        /// <summary>
        /// 服务运行状态检查属性
        /// </summary>
        public bool IsServiceRunning
        {
            get => _isServiceRunning;
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        /// <summary>
        /// 构造函数
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
            
            // 初始化DataGrid数据源
            DnsRecordsDataGrid.ItemsSource = _dnsRecords;
            RecentQueriesDataGrid.ItemsSource = _recentQueries;
            
            // 设置初始按钮文本
            UpdateServiceButtonText();
            
            // 设置刷新定时器
            _refreshTimer = new System.Threading.Timer(RefreshData, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
            
            // 初始化日志监控
            InitializeLogMonitoring();
            
            // 加载配置
            LoadSettings();
            LoadDnsRecords();
            
            // 添加窗口激活事件处理
            this.Activated += MainWindow_Activated;
        }

        /// <summary>
        /// 属性变更通知
        /// </summary>
        /// <param name="propertyName">属性名称</param>
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        private async void StartService()
        {
            try
            {
                // 在启动前检查端口是否被系统服务或进程占用
                int listenPort = 53;
                try
                {
                    // 尝试从UI读取端口
                    Dispatcher.Invoke(() =>
                    {
                        if (int.TryParse(ListenPortInput.Text, out var p) && p > 0 && p < 65536)
                        {
                            listenPort = p;
                        }
                    });
                }
                catch { /* 读取端口失败时使用默认值 */ }

                var portUsage = await CheckPortUsedBySystemServiceAsync(listenPort);
                if (portUsage.Used)
                {
                    MessageBox.Show($"检测到端口 {listenPort} 被系统服务或进程占用：\n{portUsage.Details}\n\n请更换端口（例如 1053）或停止对应服务后再启动。", "端口占用", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 显示启动中状态
                await Dispatcher.InvokeAsync(() =>
                {
                    ServiceStatusText.Text = "启动中...";
                    ServiceStatusText.Foreground = System.Windows.Media.Brushes.Orange;
                });

                // 直接运行服务进程（不通过 START 命令）
                string result = await DirectStartServiceAsync();

                // 更新UI
                await Dispatcher.InvokeAsync(() =>
                {
                    if (result.Contains("OK") || result.Contains("成功") || result.Contains("服务启动成功") || result.Contains("服务已在运行"))
                    {
                        ServiceStatusText.Text = "运行中";
                        ServiceStatusText.Foreground = System.Windows.Media.Brushes.Green;
                        ServiceRunning = true;
                        _serviceStartTime = DateTime.Now;
                        _logger.Info("DNS服务启动成功（直接运行EXE）");
                    }
                    else
                    {
                        ServiceStatusText.Text = "启动失败";
                        ServiceStatusText.Foreground = System.Windows.Media.Brushes.Red;
                        _logger.Error($"启动服务失败: {result}");
                        string errorDetails = $"启动服务失败:\n\n{result}\n\n请检查:\n1. 是否有其他DNS服务占用端口{listenPort}\n2. 是否以管理员权限运行\n3. 查看logs目录下的日志文件获取更多详情";
                        MessageBox.Show(errorDetails, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "直接启动服务时发生异常");
                MessageBox.Show($"启动服务失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task<string> DirectStartServiceAsync()
        {
            // 基准目录：UI可执行所在目录
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string? rootDir = null;
            try
            {
                var dir = new DirectoryInfo(baseDir);
                for (int i = 0; i < 6 && dir != null; i++)
                {
                    if (File.Exists(Path.Combine(dir.FullName, "LocalDnsService.csproj")))
                    {
                        rootDir = dir.FullName;
                        break;
                    }
                    dir = dir.Parent;
                }
            }
            catch { /* 忽略目录遍历异常 */ }
            
            // 候选路径列表（优先EXE，其次DLL；优先Release）
            var candidates = new List<(string path, bool isExe)>
            {
                (Path.Combine(baseDir, "LocalDnsService.exe"), true),
                (Path.Combine(baseDir, "LocalDnsService.dll"), false)
            };
            if (!string.IsNullOrWhiteSpace(rootDir))
            {
                candidates.Add((Path.Combine(rootDir, "bin", "Debug", "net8.0", "win-x64", "LocalDnsService.exe"), true));
                candidates.Add((Path.Combine(rootDir, "bin", "Debug", "net8.0", "win-x64", "LocalDnsService.dll"), false));
            }
            
            foreach (var c in candidates)
            {
                if (File.Exists(c.path))
                {
                    return c.isExe
                        ? await RunServiceAsync(c.path, "")
                        : await RunServiceAsync("dotnet", $"\"{c.path}\"");
                }
            }
            
            return "找不到LocalDnsService可执行文件或DLL文件";
        }


        /// <summary>
        /// 通过进程通信执行命令
        /// </summary>
        /// <param name="command">要执行的命令</param>
        /// <returns>命令执行结果</returns>
        private async Task<string> ExecuteCommandThroughProcessAsync(string command)
        {
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string? rootDir = null;
            try
            {
                var dir = new DirectoryInfo(baseDir);
                for (int i = 0; i < 6 && dir != null; i++)
                {
                    if (File.Exists(Path.Combine(dir.FullName, "LocalDnsService.csproj")))
                    {
                        rootDir = dir.FullName;
                        break;
                    }
                    dir = dir.Parent;
                }
            }
            catch { }
            
            var candidates = new List<(string path, bool isExe)>
            {
                (Path.Combine(baseDir, "LocalDnsService.exe"), true),
                (Path.Combine(baseDir, "LocalDnsService.dll"), false)
            };
            if (!string.IsNullOrWhiteSpace(rootDir))
            {
                candidates.Add((Path.Combine(rootDir, "bin", "Release", "net8.0-windows", "win-x64", "LocalDnsService.exe"), true));
                candidates.Add((Path.Combine(rootDir, "bin", "Release", "net8.0-windows", "win-x64", "LocalDnsService.dll"), false));
                candidates.Add((Path.Combine(rootDir, "bin", "Release", "net8.0", "LocalDnsService.exe"), true));
                candidates.Add((Path.Combine(rootDir, "bin", "Release", "net8.0", "LocalDnsService.dll"), false));
                candidates.Add((Path.Combine(rootDir, "bin", "Debug", "net8.0-windows", "win-x64", "LocalDnsService.exe"), true));
                candidates.Add((Path.Combine(rootDir, "bin", "Debug", "net8.0-windows", "win-x64", "LocalDnsService.dll"), false));
                candidates.Add((Path.Combine(rootDir, "bin", "Debug", "net8.0", "LocalDnsService.dll"), false));
            }
            
            foreach (var c in candidates)
            {
                if (File.Exists(c.path))
                {
                    if (string.Equals(command, "START", StringComparison.OrdinalIgnoreCase))
                    {
                        return c.isExe
                            ? await RunServiceAsync(c.path, "")
                            : await RunServiceAsync("dotnet", $"\"{c.path}\"");
                    }
                    return c.isExe
                        ? await RunProcessAsync(c.path, $"--command {command}")
                        : await RunProcessAsync("dotnet", $"\"{c.path}\" --command {command}");
                }
            }
            
            throw new FileNotFoundException("找不到LocalDnsService可执行文件或DLL文件");
        }

        /// <summary>
        /// 通过Named Pipes与服务通信执行命令
        /// </summary>
        /// <param name="command">要执行的命令</param>
        /// <returns>命令执行结果</returns>
        private async Task<string> ExecuteCommandThroughPipeAsync(string command)
        {
            const string pipeName = "LocalDnsServicePipe";
            try
            {
                using var pipe = new System.IO.Pipes.NamedPipeClientStream(".", pipeName, System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.Asynchronous);
                // 尝试连接，最多1秒
                await pipe.ConnectAsync(1000);
                using var reader = new StreamReader(pipe, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true);
                using var writer = new StreamWriter(pipe, Encoding.UTF8, bufferSize: 1024, leaveOpen: true) { AutoFlush = true };
                await writer.WriteLineAsync(command);
                var sb = new StringBuilder();
                string? line;
                // 读取直到服务端发送 __END__ 结束标记
                while ((line = await reader.ReadLineAsync()) != null)
                {
                    if (string.Equals(line, "__END__", StringComparison.Ordinal))
                        break;
                    sb.AppendLine(line);
                }
                return sb.ToString().TrimEnd();
            }
            catch (TimeoutException)
            {
                return "ERROR: 连接服务管道超时";
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "通过管道执行命令发生异常");
                return $"ERROR: {ex.Message}";
            }
        }

        /// <summary>
        /// 根据服务状态选择使用Named Pipes或进程通信执行命令
        /// START命令在服务未运行时仍采用启动进程的方式。
        /// </summary>
        private async Task<string> ExecuteCommandAsync(string command)
        {
            try
            {
                // 启动命令始终通过直接启动服务进程处理
                if (string.Equals(command, "START", StringComparison.OrdinalIgnoreCase))
                {
                    return await DirectStartServiceAsync();
                }
                
                // 统一走IPC：尝试通过Named Pipe发送命令
                var pipeResult = await ExecuteCommandThroughPipeAsync(command);
                if (string.IsNullOrWhiteSpace(pipeResult))
                {
                    return "ERROR: 服务未返回结果或IPC通信失败";
                }
                // 若服务返回错误，直接向上抛出，不再回退到进程通信
                if (pipeResult.StartsWith("ERROR", StringComparison.OrdinalIgnoreCase))
                {
                    return pipeResult;
                }
                return pipeResult;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "执行命令(IPC)时发生异常");
                return "ERROR: IPC执行命令失败，可能服务未运行或管道不可用";
            }
        }
        
        /// <summary>
        /// 运行DNS服务（长期运行的进程）
        /// </summary>
        /// <param name="fileName">可执行文件名</param>
        /// <param name="arguments">命令行参数</param>
        /// <returns>启动结果</returns>
        private async Task<string> RunServiceAsync(string fileName, string arguments)
        {
            StringBuilder outputBuilder = new();
            StringBuilder errorBuilder = new StringBuilder();
            bool hasStartedSuccessfully = false;
            
            var process = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo
                {
                    FileName = fileName,
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };
            
            process.OutputDataReceived += (sender, args) =>
            {
                if (!string.IsNullOrEmpty(args.Data))
                {
                    outputBuilder.AppendLine(args.Data);
                    _logger.Debug($"服务输出: {args.Data}");
                    // 检查是否启动成功
                    if (args.Data.Contains("DNS服务已成功启动") || args.Data.Contains("监听端口"))
                    {
                        hasStartedSuccessfully = true;
                    }
                    // 实时更新日志UI
                    UpdateLogUI(args.Data);
                }
            };
            
            process.ErrorDataReceived += (sender, args) =>
            {
                if (!string.IsNullOrEmpty(args.Data))
                {
                    errorBuilder.AppendLine(args.Data);
                    _logger.Error($"服务错误: {args.Data}");
                    // 实时更新日志UI
                    UpdateLogUI($"[ERROR] {args.Data}");
                }
            };
            
            try
            {
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                
                // 等待最多3秒来确认服务是否成功启动
                for (int i = 0; i < 30; i++)
                {
                    await Task.Delay(100);
                    
                    // 检查是否有错误输出，特别是服务已在运行的提示
                    string errorOutput = errorBuilder.ToString();
                    if (errorOutput.Length > 0)
                    {
                        // 检查是否包含服务已在运行的消息
                        if (errorOutput.Contains("DNS服务已经在运行中") || errorOutput.Contains("服务已经在运行"))
                        {
                            _logger.Info("检测到服务已经在运行中");
                            return "服务已在运行";
                        }
                        // 其他错误
                        if (errorOutput.Contains("Error"))
                        {
                            return errorOutput.Trim();
                        }
                    }
                    
                    if (hasStartedSuccessfully)
                    {
                        break;
                    }
                }
                
                // 检查端口53是否被占用（作为服务是否运行的另一个指标）
                bool isPortInUse = await IsPortInUse(53);
                
                // 检查是否有相同名称的进程在运行
                bool serviceProcessExists = System.Diagnostics.Process.GetProcessesByName(SERVICE_PROCESS_NAME).Length > 0;
                
                // 更准确的启动成功判断：日志显示启动成功、端口被占用或进程存在
                if (hasStartedSuccessfully || isPortInUse || serviceProcessExists)
                {
                    return serviceProcessExists && !hasStartedSuccessfully ? "服务已在运行" : "服务启动成功";
                }
                
                return outputBuilder.ToString().Trim();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "启动服务进程时发生异常");
                return $"启动服务失败: {ex.Message}";
            }
        }
        
        /// <summary>
        /// 检查端口是否被占用
        /// </summary>
        /// <param name="port">要检查的端口</param>
        /// <returns>端口是否被占用</returns>
        private async Task<bool> IsPortInUse(int port)
        {
            try
            {
                // 尝试TCP连接
                using (var tcpSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, 
                                                                   System.Net.Sockets.SocketType.Stream, 
                                                                   System.Net.Sockets.ProtocolType.Tcp))
                {
                    await tcpSocket.ConnectAsync("127.0.0.1", port);
                    tcpSocket.Close();
                    return true;
                }
            }
            catch
            {
                // TCP连接失败，尝试检查是否有进程在监听这个端口
                try
                {
                    System.Net.NetworkInformation.IPGlobalProperties ipGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
                    System.Net.IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
                    
                    // 检查是否有进程在监听指定端口
                    return tcpConnInfoArray.Any(endPoint => endPoint.Port == port);
                }
                catch
                {
                    return false;
                }
            }
        }
        
        /// <summary>
        /// 尝试使用不同的编码打开日志文件，解决乱码问题
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <returns>能够正确读取文件的StreamReader</returns>
        private StreamReader TryOpenWithDifferentEncodings(FileStream stream)
        {
            // 保存当前流位置
            long position = stream.Position;
            
            // 尝试的编码列表
            Encoding[] encodingsToTry = new[]
            {
                Encoding.UTF8,
                Encoding.GetEncoding(936), // GBK
                Encoding.GetEncoding(54936), // GB18030
                Encoding.Default, // 系统默认编码
                Encoding.Unicode
            };
            
            foreach (var encoding in encodingsToTry)
            {
                try
                {
                    // 重置流位置
                    stream.Position = position;
                    
                    // 创建新的StreamReader
                    var reader = new StreamReader(stream, encoding, true);
                    
                    // 尝试读取一小部分内容
                    string testContent = reader.ReadToEnd();
                    
                    // 如果能成功读取且包含有效字符，就使用这个编码
                    if (!string.IsNullOrWhiteSpace(testContent) && ContainsValidChars(testContent))
                    {
                        // 重置流位置
                        stream.Position = position;
                        return new StreamReader(stream, encoding, false);
                    }
                }
                catch
                {
                    // 忽略错误，尝试下一个编码
                }
            }
            
            // 如果所有编码都失败，重置流位置并使用UTF8作为默认
            stream.Position = position;
            return new StreamReader(stream, Encoding.UTF8);
        }
        
        /// <summary>
        /// 检查字符串是否包含有效字符（非乱码）
        /// </summary>
        /// <param name="text">要检查的文本</param>
        /// <returns>是否包含有效字符</returns>
        private bool ContainsValidChars(string text)
        {
            // 检查是否包含常见的日志关键字
            string[] commonLogKeywords = { "[INFO]", "[ERROR]", "[DEBUG]", "DNS", "服务", "启动", "监听" };
            
            foreach (string keyword in commonLogKeywords)
            {
                if (text.Contains(keyword))
                {
                    return true;
                }
            }
            
            // 检查是否包含大量控制字符或无效字符
            int invalidCharCount = 0;
            foreach (char c in text)
            {
                if ((c >= 0x00 && c <= 0x1F) && !char.IsWhiteSpace(c))
                {
                    invalidCharCount++;
                }
            }
            
            // 如果无效字符比例超过10%，认为是乱码
            return invalidCharCount < text.Length * 0.1;
        }
        
        /// <summary>
        /// 更新日志UI
        /// </summary>
        /// <param name="logLine">日志行</param>
        private void UpdateLogUI(string logLine)
        {
            _logger.Info(logLine);
        }
        
        /// <summary>
        /// 运行外部进程并获取输出
        /// </summary>
        /// <param name="fileName">可执行文件名</param>
        /// <param name="arguments">命令行参数</param>
        /// <returns>进程输出结果</returns>
        private async Task<string> RunProcessAsync(string fileName, string arguments)
        {
            // 由于需要捕获输出，我们设置UseShellExecute=false
            // 但由于UI已经检查了管理员权限，如果UI以管理员身份运行，启动的进程也会继承这些权限
            var process = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo
                {
                    FileName = fileName,
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };
            
            StringBuilder outputBuilder = new();
            StringBuilder errorBuilder = new StringBuilder();
            
            process.OutputDataReceived += (sender, args) =>
            {
                if (!string.IsNullOrEmpty(args.Data))
                    outputBuilder.AppendLine(args.Data);
            };
            
            process.ErrorDataReceived += (sender, args) =>
            {
                if (!string.IsNullOrEmpty(args.Data))
                    errorBuilder.AppendLine(args.Data);
            };
            
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            
            // 等待进程完成，最多等待5秒
            await Task.Run(() => process.WaitForExit(5000));
            
            // 如果进程还在运行，尝试终止
            if (!process.HasExited)
            {
                try
                {
                    process.Kill();
                }
                catch { }
            }
            
            string output = outputBuilder.ToString();
            string error = errorBuilder.ToString();
            
            // 如果有错误输出，返回错误信息
            if (!string.IsNullOrEmpty(error))
            {
                return error.Trim();
            }
            
            return output.Trim();
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        private async void StopService()
        {
            try
            {
                // 检查是否以管理员权限运行
                if (!IsRunningAsAdministrator())
                {
                    MessageBox.Show("停止DNS服务需要管理员权限，请以管理员身份运行此程序。", "权限不足", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                // 记录停止服务的日志
                _logger.Info("开始停止DNS服务");
                
                // 通过进程通信执行STOP命令
                string result = await ExecuteCommandAsync("STOP");
                
                // 更新UI
                await Dispatcher.InvokeAsync(() =>
                {
                    if (result.Contains("OK") || result.Contains("成功") || result.Contains("已停止"))
                    {
                        ServiceStatusText.Text = "已停止";
                        ServiceStatusText.Foreground = System.Windows.Media.Brushes.Gray;
                        ServiceRunning = false;
                        _serviceStartTime = null;
                        UptimeText.Text = "00:00:00";
                    }
                    else
                    {
                        // 即使命令执行失败，也尝试检查进程状态
                        var processes = System.Diagnostics.Process.GetProcessesByName(SERVICE_PROCESS_NAME);
                        if (processes.Length == 0)
                        {
                            // 没有找到进程，认为服务已停止
                            ServiceStatusText.Text = "已停止";
                            ServiceStatusText.Foreground = System.Windows.Media.Brushes.Gray;
                            ServiceRunning = false;
                            _serviceStartTime = null;
                            UptimeText.Text = "00:00:00";
                        }
                        else
                        {
                            // 命令执行失败但进程仍在运行，显示错误
                            ServiceStatusText.Text = "停止失败";
                            ServiceStatusText.Foreground = System.Windows.Media.Brushes.Red;
                            MessageBox.Show($"停止服务失败: {result}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    UpdateServiceButtonText();
                });
            }
            catch (Exception ex)
            {
                // 异常情况下，尝试强制停止进程作为后备方案
                    try
                    {
                        var processes = System.Diagnostics.Process.GetProcessesByName(SERVICE_PROCESS_NAME);
                        if (processes.Length > 0)
                        {
                            foreach (var process in processes)
                            {
                                try
                                {
                                    process.Kill();
                                    process.WaitForExit(1000);
                                }
                                catch { }
                            }
                        }
                    
                    await Dispatcher.InvokeAsync(() =>
                    {
                        ServiceStatusText.Text = "已停止";
                        ServiceStatusText.Foreground = System.Windows.Media.Brushes.Gray;
                        ServiceRunning = false;
                        _serviceStartTime = null;
                        UptimeText.Text = "00:00:00";
                        UpdateServiceButtonText();
                    });
                }
                catch
                {
                    // 如果强制停止也失败，显示错误
                    await Dispatcher.InvokeAsync(() =>
                    {
                        ServiceStatusText.Text = "停止失败";
                        ServiceStatusText.Foreground = System.Windows.Media.Brushes.Red;
                    });
                    MessageBox.Show($"停止服务失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        private async void RefreshData(object? state)
        {
            try
            {
                // 使用增强的服务状态检查方法（异步避免阻塞UI线程）
                var isRunning = await CheckServiceRunningAsync();
                
                Dispatcher.Invoke(() =>
                {
                    // 如果服务状态发生变化
                    if (isRunning != _serviceRunning)
                    {
                        ServiceStatusText.Text = isRunning ? "运行中" : "已停止";
                        ServiceStatusText.Foreground = isRunning ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Gray;
                        ServiceRunning = isRunning;
                        UpdateServiceButtonText();
                        
                        // 如果服务刚刚启动，记录启动时间
                        if (isRunning && !_serviceStartTime.HasValue)
                        {
                            _serviceStartTime = DateTime.Now;
                        }
                        // 如果服务刚刚停止，重置启动时间
                        else if (!isRunning)
                        {
                            _serviceStartTime = null;
                            UptimeText.Text = "00:00:00";
                        }
                    }
                    
                    // 更新运行时间
                    if (isRunning && _serviceStartTime.HasValue)
                    {
                        var uptime = DateTime.Now - _serviceStartTime.Value;
                        UptimeText.Text = $"{uptime.Hours:D2}:{uptime.Minutes:D2}:{uptime.Seconds:D2}";
                    }
                    
                    // 刷新日志内容
                    if (isRunning)
                    {
                        UpdateLogView();
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "刷新数据时发生异常");
                // 忽略错误，避免影响其他功能
            }
        }

        /// <summary>
        /// 加载DNS记录
        /// </summary>
        private void LoadDnsRecords()
        {
            try
            {
                // 从配置文件加载DNS记录，使用灵活的路径查找策略
                var dnsConfigPath = GetConfigFilePath("dns.conf");
                if (File.Exists(dnsConfigPath))
                {
                    var lines = File.ReadAllLines(dnsConfigPath);
                    _dnsRecords.Clear();
                    
                    foreach (var line in lines.Where(l => !string.IsNullOrWhiteSpace(l) && !l.StartsWith("#")))
                    {
                        var parts = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                        if (parts.Length >= 3)
                        {
                            _dnsRecords.Add(new DnsRecordViewModel
                            {
                                // 配置格式：IP地址 域名 [记录类型] [TTL]
                                // 1.2.3.4 example.com A 300
                                // 映射：Value=IP地址，Domain=域名，Type=记录类型
                                Domain = parts[1],
                                Type = parts[2],
                                Value = parts[0]
                            });
                        }
                    }
                    
                    Dispatcher.Invoke(() =>
                    {
                        DnsRecordsDataGrid.Items.Refresh();
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载DNS记录失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 保存DNS记录（通过IPC：清空后重新导入当前列表）
        /// </summary>
        private async Task SaveDnsRecordsAsync()
        {
            try
            {
                // 1) 清空服务端记录（服务端在启用持久化时会导出到文件）
                var clearResult = await ExecuteCommandAsync("CLEAR_RECORDS");
                if (string.IsNullOrWhiteSpace(clearResult) || (!clearResult.Contains("OK") && !clearResult.Contains("成功")))
                {
                    MessageBox.Show(string.IsNullOrWhiteSpace(clearResult) ? "清空现有记录失败" : clearResult, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                
                // 2) 逐条重新添加当前UI中的记录
                foreach (var r in _dnsRecords)
                {
                    if (string.IsNullOrWhiteSpace(r.Domain) || string.IsNullOrWhiteSpace(r.Type) || string.IsNullOrWhiteSpace(r.Value))
                        continue;
                    
                    string cmd = r.Type.Equals("PTR", StringComparison.OrdinalIgnoreCase)
                        ? $"ADD_PTR {r.Value} {r.Domain}"
                        : $"ADD {r.Domain} {r.Value}";
                    var addResult = await ExecuteCommandAsync(cmd);
                    if (string.IsNullOrWhiteSpace(addResult) || (!addResult.Contains("OK") && !addResult.Contains("成功")))
                    {
                        MessageBox.Show(string.IsNullOrWhiteSpace(addResult) ? $"添加记录失败：{r.Domain}" : addResult, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }
                
                MessageBox.Show("DNS记录已通过IPC保存并同步到服务", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                await Task.Delay(100);
                LoadDnsRecords();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存DNS记录失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 保存DNS记录
        /// </summary>
        private void SaveDnsRecords()
        {
            try
            {
                var dnsConfigPath = GetConfigFilePath("dns.conf");
                // 确保Conf目录存在
                string? dirPath = Path.GetDirectoryName(dnsConfigPath);
                if (!string.IsNullOrEmpty(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                var lines = _dnsRecords.Select(r => $"{r.Value} {r.Domain} {r.Type}");
                File.WriteAllLines(dnsConfigPath, lines);
                MessageBox.Show("DNS记录保存成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存DNS记录失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 加载设置
        /// </summary>
        private void LoadSettings()
        {
            try
            {
                var configPath = GetConfigFilePath("DNSService.conf");
                if (File.Exists(configPath))
                {
                    var lines = File.ReadAllLines(configPath);
                    
                    foreach (var line in lines.Where(l => !string.IsNullOrWhiteSpace(l) && !l.StartsWith("#")))
                    {
                        var parts = line.Split('=', 2);
                        if (parts.Length == 2)
                        {
                            var key = parts[0].Trim();
                            var value = parts[1].Trim();
                            
                            switch (key)
                            {
                                case "ListenPort":
                                    Dispatcher.Invoke(() => ListenPortInput.Text = value);
                                    break;
                                case "CacheSize":
                                    Dispatcher.Invoke(() => CacheSizeInput.Text = value);
                                    break;
                                case "CacheTTL":
                                    Dispatcher.Invoke(() => CacheTTLInput.Text = value);
                                    break;
                                case "UpstreamDNS":
                                    Dispatcher.Invoke(() => PrimaryUpstreamDnsInput.Text = value);
                                    break;
                                case "SecondaryUpstreamDNS":
                                    Dispatcher.Invoke(() => SecondaryUpstreamDnsInput.Text = value);
                                    break;
                                case "EnableIPv6":
                                    Dispatcher.Invoke(() => EnableIPv6Checkbox.IsChecked = value.Equals("true", StringComparison.OrdinalIgnoreCase));
                                    break;
                                case "EnableTCP":
                                    Dispatcher.Invoke(() => EnableTCPCheckbox.IsChecked = value.Equals("true", StringComparison.OrdinalIgnoreCase));
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载设置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 保存设置
        /// </summary>
        private void SaveSettings()
        {
            try
            {
                var configPath = GetConfigFilePath("DNSService.conf");
                // 确保Conf目录存在
                string? dirPath = Path.GetDirectoryName(configPath);
                if (!string.IsNullOrEmpty(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                var settings = new Dictionary<string, string>
                {
                    { "ListenPort", ListenPortInput.Text },
                    { "CacheSize", CacheSizeInput.Text },
                    { "CacheTTL", CacheTTLInput.Text },
                    { "UpstreamDNS", PrimaryUpstreamDnsInput.Text },
                    { "SecondaryUpstreamDNS", SecondaryUpstreamDnsInput.Text },
                    { "EnableIPv6", EnableIPv6Checkbox.IsChecked?.ToString().ToLowerInvariant() ?? "false" },
                    { "EnableTCP", EnableTCPCheckbox.IsChecked?.ToString().ToLowerInvariant() ?? "false" }
                };
                
                var lines = settings.Select(kv => $"{kv.Key}={kv.Value}");
                File.WriteAllLines(configPath, lines);
                MessageBox.Show("设置保存成功，请重启服务以应用更改", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存设置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #region 辅助方法

        /// <summary>
        /// 检查程序是否以管理员权限运行
        /// </summary>
        /// <returns>如果以管理员权限运行则返回true</returns>
        private bool IsRunningAsAdministrator()
        {
            var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            var principal = new System.Security.Principal.WindowsPrincipal(identity);
            return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }

        /// <summary>
        /// 更新服务按钮文本
        /// </summary>
        private void UpdateServiceButtonText()
        {
            ServiceToggleButton.Content = ServiceRunning ? "停止服务" : "启动服务";
        }

        /// <summary>
        /// 检查指定端口是否被系统服务或进程占用，并返回详细说明
        /// </summary>
        /// <param name="port">端口号</param>
        /// <returns>Used: 是否被占用；Details: 详细占用信息</returns>
        private async Task<(bool Used, string Details)> CheckPortUsedBySystemServiceAsync(int port)
        {
            try
            {
                var pids = await GetPidsListeningOnPortAsync(port);
                if (pids.Count == 0)
                {
                    return (false, string.Empty);
                }

                var sb = new StringBuilder();
                foreach (var pid in pids.Distinct())
                {
                    string processName = string.Empty;
                    try
                    {
                        processName = System.Diagnostics.Process.GetProcessById(pid).ProcessName;
                    }
                    catch { }

                    string serviceName = string.Empty;
                    string displayName = string.Empty;
                    try
                    {
                        (serviceName, displayName) = TryGetServiceInfoByPid(pid);
                    }
                    catch { }

                    if (!string.IsNullOrWhiteSpace(serviceName))
                    {
                        sb.AppendLine($"- 服务: {displayName} ({serviceName}), PID: {pid}");
                    }
                    else
                    {
                        sb.AppendLine($"- 进程: {processName}, PID: {pid}");
                    }
                }

                return (true, sb.ToString().Trim());
            }
            catch (Exception ex)
            {
                _logger.Warn(ex, $"检测端口占用（{port}）时发生异常");
                return (false, string.Empty);
            }
        }

        /// <summary>
        /// 获取监听指定端口的PID列表（TCP/UDP）
        /// </summary>
        private async Task<List<int>> GetPidsListeningOnPortAsync(int port)
        {
            var result = new List<int>();

            // 查询TCP监听
            result.AddRange(await GetPidsFromNetstatAsync($"-ano -p tcp", port, requireListeningState: true));
            // 查询UDP端点
            result.AddRange(await GetPidsFromNetstatAsync($"-ano -p udp", port, requireListeningState: false));

            return result;
        }

        /// <summary>
        /// 解析 netstat 输出，抽取指定端口对应的PID
        /// </summary>
        private async Task<List<int>> GetPidsFromNetstatAsync(string arguments, int port, bool requireListeningState)
        {
            var pids = new List<int>();
            try
            {
                var psi = new System.Diagnostics.ProcessStartInfo
                {
                    FileName = "netstat",
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };

                using var proc = System.Diagnostics.Process.Start(psi);
                if (proc == null)
                {
                    return pids;
                }

                string output = await proc.StandardOutput.ReadToEndAsync();
                string error = await proc.StandardError.ReadToEndAsync();
                proc.WaitForExit(2000);

                if (!string.IsNullOrWhiteSpace(error))
                {
                    _logger.Debug($"netstat错误: {error}");
                }

                var lines = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var raw in lines)
                {
                    var line = raw.Trim();
                    if (!(line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase) || line.StartsWith("UDP", StringComparison.OrdinalIgnoreCase)))
                        continue;

                    // 简化多空格为单空格
                    var parts = System.Text.RegularExpressions.Regex.Split(line, "\\s+");
                    if (parts.Length < 4) continue;

                    string localAddress = parts[1];
                    string stateOrForeign = parts.Length >= 4 ? parts[3] : string.Empty;

                    bool portMatch = localAddress.EndsWith($":{port}") || localAddress.EndsWith($"]:{port}");
                    if (!portMatch) continue;

                    if (requireListeningState && !string.Equals(stateOrForeign, "LISTENING", StringComparison.OrdinalIgnoreCase))
                        continue;

                    // PID 通常是最后一个字段
                    string pidStr = parts[^1];
                    if (int.TryParse(pidStr, out var pid) && pid > 0)
                    {
                        pids.Add(pid);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Warn(ex, $"解析netstat输出失败: args={arguments}");
            }
            return pids;
        }

        /// <summary>
        /// 通过WMI根据PID查找对应的Windows服务信息
        /// </summary>
        private (string serviceName, string displayName) TryGetServiceInfoByPid(int pid)
        {
            try
            {
                using var searcher = new ManagementObjectSearcher($"SELECT Name, DisplayName FROM Win32_Service WHERE ProcessId = {pid}");
                foreach (ManagementObject svc in searcher.Get())
                {
                    string name = svc["Name"]?.ToString() ?? string.Empty;
                    string display = svc["DisplayName"]?.ToString() ?? name;
                    return (name, display);
                }
            }
            catch (Exception ex)
            {
                _logger.Debug(ex, "WMI查询服务信息失败");
            }
            return (string.Empty, string.Empty);
        }

        #endregion

        #region 事件处理

        private async void ServiceToggleButton_Click(object? sender, RoutedEventArgs e)
        {
            // 再次检查服务状态，确保准确性（异步避免阻塞UI线程）
            bool isActuallyRunning = await CheckServiceRunningAsync();
            
            // 如果检测到的状态与当前UI显示的状态不一致，先更新UI
            if (isActuallyRunning != IsServiceRunning)
            {
                _logger.Warn($"检测到服务状态不一致: UI显示={IsServiceRunning}, 实际状态={isActuallyRunning}");
                ServiceRunning = isActuallyRunning;
                UpdateServiceButtonText();
                
                // 显示提示消息
                if (isActuallyRunning && !IsServiceRunning)
                {
                    MessageBox.Show("检测到服务已在运行中，UI状态已更新。", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            
            // 基于更新后的状态执行相应操作
            if (IsServiceRunning)
            {
                StopService();
            }
            else
            {
                StartService();
            }
        }

        private async void AddRecordButton_Click(object? sender, RoutedEventArgs e)
        {
            var domain = DomainInput.Text?.Trim();
            var ipOrValue = RecordValueInput.Text?.Trim();
            var type = (RecordTypeComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString();
            
            if (string.IsNullOrWhiteSpace(domain) || string.IsNullOrWhiteSpace(ipOrValue) || string.IsNullOrWhiteSpace(type))
            {
                MessageBox.Show("请填写完整的记录信息", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            
            string command = type.Equals("PTR", StringComparison.OrdinalIgnoreCase)
                ? $"ADD_PTR {ipOrValue} {domain}"
                : $"ADD {domain} {ipOrValue}";
            
            var result = await ExecuteCommandAsync(command);
            if (!string.IsNullOrWhiteSpace(result) && (result.Contains("OK") || result.Contains("成功")))
            {
                MessageBox.Show("记录添加成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                // 刷新列表（从文件加载）
                await Task.Delay(100);
                LoadDnsRecords();
                // 清空输入并重置类型为A
                DomainInput.Clear();
                RecordValueInput.Clear();
                RecordTypeComboBox.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show(string.IsNullOrWhiteSpace(result) ? "添加失败" : result, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void DeleteRecordButton_Click(object? sender, RoutedEventArgs e)
        {
            if (DnsRecordsDataGrid.SelectedItem is DnsRecordViewModel record && !string.IsNullOrWhiteSpace(record.Domain))
            {
                var result = await ExecuteCommandAsync($"REMOVE {record.Domain}");
                if (!string.IsNullOrWhiteSpace(result) && (result.Contains("OK") || result.Contains("成功")))
                {
                    MessageBox.Show("记录删除成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    await Task.Delay(100);
                    LoadDnsRecords();
                }
                else
                {
                    MessageBox.Show(string.IsNullOrWhiteSpace(result) ? "删除失败" : result, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private async void SaveRecordsButton_Click(object? sender, RoutedEventArgs e)
        {
            await SaveDnsRecordsAsync();
        }

        private void SaveSettingsButton_Click(object? sender, RoutedEventArgs e)
        {
            SaveSettings();
        }
        
        private void DnsRecordsDataGrid_SelectionChanged(object? sender, SelectionChangedEventArgs e)
        {
            if (DnsRecordsDataGrid.SelectedItem is DnsRecordViewModel record)
            {
                // 将选中项填充到编辑区
                DomainInput.Text = record.Domain;
                RecordValueInput.Text = record.Value;
                // 设置类型选择
                for (int i = 0; i < RecordTypeComboBox.Items.Count; i++)
                {
                    if ((RecordTypeComboBox.Items[i] as ComboBoxItem)?.Content?.ToString()?.Equals(record.Type, StringComparison.OrdinalIgnoreCase) == true)
                    {
                        RecordTypeComboBox.SelectedIndex = i;
                        break;
                    }
                }
            }
        }

        private async void EditRecordButton_Click(object? sender, RoutedEventArgs e)
        {
            if (DnsRecordsDataGrid.SelectedItem is not DnsRecordViewModel selected || string.IsNullOrWhiteSpace(selected.Domain))
            {
                MessageBox.Show("请先在下方列表选中需要修改的记录", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            
            var domain = selected.Domain;
            var newValue = RecordValueInput.Text?.Trim();
            var type = (RecordTypeComboBox.SelectedItem as ComboBoxItem)?.Content?.ToString();
            if (string.IsNullOrWhiteSpace(newValue) || string.IsNullOrWhiteSpace(type))
            {
                MessageBox.Show("请在上方输入新的类型和记录值", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            
            // 通过IPC进行修改：先删除，再添加
            var removeResult = await ExecuteCommandAsync($"REMOVE {domain}");
            if (string.IsNullOrWhiteSpace(removeResult) || (!removeResult.Contains("OK") && !removeResult.Contains("成功")))
            {
                MessageBox.Show(string.IsNullOrWhiteSpace(removeResult) ? "删除旧记录失败" : removeResult, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            
            string addCmd = type.Equals("PTR", StringComparison.OrdinalIgnoreCase)
                ? $"ADD_PTR {newValue} {domain}"
                : $"ADD {domain} {newValue}";
            var addResult = await ExecuteCommandAsync(addCmd);
            if (!string.IsNullOrWhiteSpace(addResult) && (addResult.Contains("OK") || addResult.Contains("成功")))
            {
                MessageBox.Show("记录修改并保存成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                await Task.Delay(100);
                LoadDnsRecords();
            }
            else
            {
                MessageBox.Show(string.IsNullOrWhiteSpace(addResult) ? "修改失败" : addResult, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 刷新日志按钮点击事件
        /// </summary>
        private void RefreshLogButton_Click(object? sender, RoutedEventArgs e)
        {
        }
        
        /// <summary>
        /// 清空日志按钮点击事件
        /// </summary>
        private void ClearLogButton_Click(object? sender, RoutedEventArgs e)
        {
        }
        
        /// <summary>
        /// 日志级别选择变化事件
        /// </summary>
        private void LogLevelComboBox_SelectionChanged(object? sender, SelectionChangedEventArgs e)
        {
        }

        #endregion

        /// <summary>
        /// 窗口关闭时的清理工作
        /// </summary>
        /// <summary>
        /// 窗口激活事件处理
        /// </summary>
        private void MainWindow_Activated(object? sender, EventArgs e)
        {
            // 窗口被激活时立即刷新服务状态
            _logger.Info("窗口被激活，刷新服务状态");
            RefreshData(null);
        }
        
        /// <summary>
        /// 检查服务是否正在运行
        /// </summary>
        private async Task<bool> CheckServiceRunningAsync()
        {
            try
            {
                // 方法1: 检查进程是否存在
                bool hasProcess = System.Diagnostics.Process.GetProcessesByName(SERVICE_PROCESS_NAME).Any();
                
                // 方法2: 检查端口是否被占用（使用异步避免阻塞）
                bool portInUse = await IsPortInUse(53);
                
                // 综合判断：有进程或端口被占用都认为服务在运行
                bool isRunning = hasProcess || portInUse;
                
                _logger.Debug($"服务状态检查 - 进程存在: {hasProcess}, 端口占用: {portInUse}, 综合结果: {isRunning}");
                return isRunning;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "检查服务运行状态时发生异常");
                // 异常情况下，尝试简单的进程检查
                return System.Diagnostics.Process.GetProcessesByName(SERVICE_PROCESS_NAME).Any();
            }
        }
        
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            _refreshTimer?.Dispose();
            _httpClient?.Dispose();
            _logFileWatcher?.Dispose();
            // 移除事件处理
            this.Activated -= MainWindow_Activated;
        }
        
        /// <summary>
        /// 获取配置文件路径，使用灵活的查找策略
        /// </summary>
        /// <param name="fileName">配置文件名</param>
        /// <returns>配置文件的完整路径</returns>
        private string GetConfigFilePath(string fileName)
        {
            // 尝试多个可能的配置文件路径
            string[] possiblePaths = new[]
            {
                // 1. 在项目根目录下的Conf文件夹（优先使用主项目的配置）
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "..", "Conf", fileName),
                // 2. 在应用程序基目录的上级目录
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "Conf", fileName),
                // 3. 在当前工作目录下的Conf文件夹
                Path.Combine(Environment.CurrentDirectory, "Conf", fileName),
                // 4. 在应用程序基目录下的Conf文件夹
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Conf", fileName)
            };
            
            foreach (var path in possiblePaths)
            {
                string fullPath = Path.GetFullPath(path);
                if (File.Exists(fullPath))
                {
                    return fullPath;
                }
            }
            
            // 如果所有路径都不存在，优先返回项目根目录下的Conf文件夹路径
            // 这样可以确保使用主项目的配置目录结构
            string projectRootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "..", "Conf", fileName);
            string projectRootFullPath = Path.GetFullPath(projectRootPath);
            
            // 确保父目录存在
            string? projectRootDir = Path.GetDirectoryName(projectRootFullPath);
            if (!string.IsNullOrEmpty(projectRootDir))
            {
                return projectRootFullPath;
            }
            
            // 作为最后的备选方案
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "Conf", fileName);
        }
        
        #region 日志相关方法
        
        /// <summary>
        /// 初始化日志监控
        /// </summary>
        private void InitializeLogMonitoring()
        {
        }
        
        /// <summary>
        /// 获取选中的日志级别
        /// </summary>
        private string GetSelectedLogLevel()
        {
            return "INFO";
        }
        
        /// <summary>
        /// 获取日志文件路径
        /// </summary>
        private string GetLogFilePath(string logLevel)
        {
            try
            {
                // 尝试多个可能的日志文件路径
                string[] possiblePaths = new[]
                {
                    // 在Debug目录下的logs文件夹
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "..", "bin", "Debug", "net8.0", "win-x64", "logs", $"dnsservice.{logLevel}.log"),
                    // 在当前目录下的logs文件夹
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", $"dnsservice.{logLevel}.log"),
                    // 直接在输出目录
                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"dnsservice.{logLevel}.log")
                };
                
                foreach (var path in possiblePaths)
                {
                    string fullPath = Path.GetFullPath(path);
                    if (File.Exists(fullPath) || (Path.GetDirectoryName(fullPath) != null && Directory.Exists(Path.GetDirectoryName(fullPath))))
                    {
                        return fullPath;
                    }
                }
                
                // 如果都不存在，返回默认路径
                return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "..", "bin", "Debug", "net8.0", "win-x64", "logs", $"dnsservice.{logLevel}.log");
            }
            catch
            {
                return string.Empty;
            }
        }
        
        /// <summary>
        /// 更新日志视图
        /// </summary>
        private void UpdateLogView()
        {
        }
        
        /// <summary>
        /// 日志文件变化事件处理
        /// </summary>
        private void LogFileChanged(object? sender, FileSystemEventArgs e)
        {
        }
        
        #endregion
    }

    #region 数据模型

    /// <summary>
    /// DNS记录视图模型
    /// </summary>
    public class DnsRecordViewModel
    {
        /// <summary>
        /// 域名
        /// </summary>
        public string? Domain { get; set; }
        
        /// <summary>
        /// 记录类型
        /// </summary>
        public string? Type { get; set; }
        
        /// <summary>
        /// 记录值
        /// </summary>
        public string? Value { get; set; }
    }

    /// <summary>
    /// 查询日志视图模型
    /// </summary>
    public class QueryLogViewModel
    {
        /// <summary>
        /// 查询域名
        /// </summary>
        public string? Domain { get; set; }
        
        /// <summary>
        /// 查询类型
        /// </summary>
        public string? Type { get; set; }
        
        /// <summary>
        /// 查询结果
        /// </summary>
        public string? Result { get; set; }
        
        /// <summary>
        /// 来源
        /// </summary>
        public string? Source { get; set; }
        
        /// <summary>
        /// 查询时间
        /// </summary>
        public string? Time { get; set; }
    }

    #endregion
}